<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Link } from '@element-plus/icons-vue'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  url: '',
  status: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const form = reactive({
  id: '',
  name: '',
  url: '',
  logo: '',
  description: '',
  status: 1,
  sort: 0
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入链接名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入链接地址', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL地址', trigger: 'blur' }
  ]
}

// 表单引用
const formRef = ref()

// 初始化数据
onMounted(() => {
  fetchData()
})

// 获取数据
const fetchData = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    tableData.value = [
      { id: 1, name: 'Vue官网', url: 'https://vuejs.org/', logo: 'https://vuejs.org/images/logo.png', description: 'Vue.js官方网站', status: 1, sort: 1, createTime: '2023-01-01 10:00:00' },
      { id: 2, name: 'Element Plus', url: 'https://element-plus.org/', logo: 'https://element-plus.org/images/element-plus-logo.svg', description: 'Element Plus组件库', status: 1, sort: 2, createTime: '2023-01-02 10:00:00' },
      { id: 3, name: 'MDN Web Docs', url: 'https://developer.mozilla.org/', logo: 'https://developer.mozilla.org/static/media/logo-wordmark.1abf1c8a.svg', description: 'Web开发者文档', status: 1, sort: 3, createTime: '2023-01-03 10:00:00' }
    ]
    pagination.total = 3
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchData()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加友情链接'
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 显示编辑对话框
const showEditDialog = (row: any) => {
  dialogTitle.value = '编辑友情链接'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  form.id = row.id
  form.name = row.name
  form.url = row.url
  form.logo = row.logo
  form.description = row.description
  form.status = row.status
  form.sort = row.sort
}

// 删除友情链接
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该友情链接吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除API请求
    setTimeout(() => {
      ElMessage.success('删除成功')
      fetchData()
    }, 500)
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      // 模拟API请求
      setTimeout(() => {
        ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
        dialogVisible.value = false
        fetchData()
      }, 500)
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = ''
  form.name = ''
  form.url = ''
  form.logo = ''
  form.description = ''
  form.status = 1
  form.sort = 0
}

// 状态格式化
const statusFormatter = (row: any) => {
  return row.status === 1 ? '显示' : '隐藏'
}

// 状态标签类型
const statusTagType = (status: number) => {
  return status === 1 ? 'success' : 'info'
}

// 访问链接
const handleVisit = (url: string) => {
  window.open(url, '_blank')
}
</script>

<template>
  <div class="links-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="链接名称">
          <el-input v-model="searchForm.name" placeholder="请输入链接名称" clearable />
        </el-form-item>
        <el-form-item label="链接地址">
          <el-input v-model="searchForm.url" placeholder="请输入链接地址" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="显示" :value="1" />
            <el-option label="隐藏" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-button type="primary" :icon="Plus" @click="showAddDialog">添加友情链接</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="链接名称" width="150" />
        <el-table-column prop="url" label="链接地址" min-width="200">
          <template #default="{ row }">
            <el-link :href="row.url" target="_blank" type="primary">{{ row.url }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="logo" label="Logo" width="120">
          <template #default="{ row }">
            <el-image v-if="row.logo" :src="row.logo" fit="contain" style="width: 80px; height: 30px;" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusFormatter(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button type="primary" :icon="Link" size="small" @click="handleVisit(row.url)">访问</el-button>
              <el-button type="success" :icon="Edit" size="small" @click="showEditDialog(row)">编辑</el-button>
              <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="链接名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入链接名称" />
        </el-form-item>
        <el-form-item label="链接地址" prop="url">
          <el-input v-model="form.url" placeholder="请输入链接地址，以http://或https://开头" />
        </el-form-item>
        <el-form-item label="Logo">
          <el-input v-model="form.logo" placeholder="请输入Logo地址" />
          <div class="image-preview" v-if="form.logo">
            <el-image :src="form.logo" fit="contain" style="width: 200px; height: 60px;" />
          </div>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.links-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

/* 搜索区域样式优化 */
.search-card .el-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-card .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

.search-card .el-form-item:last-child {
  margin-right: 0;
}

/* 增加选择框宽度 */
.search-card .el-select {
  width: 150px;
}

.operation-area {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.image-preview {
  margin-top: 10px;
}

/* 操作列按钮样式 */
.operation-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: nowrap;
  justify-content: center;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .links-container {
    padding: 10px;
  }
  
  .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .el-table .cell {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  
  .operation-area .el-button {
    margin-bottom: 10px;
  }
  
  .operation-buttons {
    flex-direction: column;
    gap: 3px;
  }
}
</style>